
import {
  request
} from "../../request";
Page({
  data: {
    hiddenmodalput: true,
    imgarray: [],
    imgarray1: [],
    imgarray2: [],
    imgarray3: [],
    shop_name: '商家信息错误',
    shop_tel: '',
    score: [2, 2, 2, 2, 2],
    score1: '0.0',
    shop_addr: "暂无地址",
    shop_time: "8:00-20:00",
    inputValue: '',
    changeid: '',
    temp: '',
    imgs:[
      {
        imgid:0,
        imgtitle:'店铺照片',
        imgArr:[],
      },
      {
        imgid:1,
        imgtitle:'店铺环境',
        imgArr:[],
      },
      {
        imgid:2,
        imgtitle:'美食一览',
        imgArr:[],
      },
    ]
  },
  onLoad: function (options) {
    console.log(options.idx)
    let a = '2.1';
    this.setData({
      score1: a
    })
    // 评定星级，以0,1,2为标识，做为放置星星的标准
    // 初始值必须都为2，这样即使后面置为空值，也能保证星星全部显示
    let temp = this.data.score;
    let judge = false;
    for (let i = 0; i < 5; i++) {
      if (!judge) {
        if (i < parseInt(a)) {
          temp[i] = 0;
        } else {
          if (parseInt(a.split('.')[1]) >= 8) {
            temp[i] = 0;
          } else if (parseInt(a.split('.')[1]) < 8 && parseInt(a.split('.')[1]) >= 3) {
            temp[i] = 1;
          }
          judge = true;
        }
      }

    }
    this.setData({
      score: temp
    })
    this.getShopData_item();
    console.log(this.data.imgarray);
  },
  calling: function () {
    wx.makePhoneCall({
      phoneNumber: this.data.shop_tel, //此号码并非真实电话号码，仅用于测试
      success: function () {
        console.log("拨打电话成功！")
      },
      fail: function () {
        console.log("拨打电话失败！")
      }
    })
  },
  async getShopData_item(idx) {
    let open_id = wx.getStorageSync('openid')
    const res = await request({
      url: '/shoppage/select',
      data: {
        open_id,
      }
    });
    console.log(res)
    //数据错误处理
    if(!res.image0){
      wx.showToast({
        title: '错误',
      })
      return 
    }
    let temp0 = [],temp1 = [],temp2 = [],temp3 = [];
    for(let i in res.image0){
      temp0[i] = 'https://fourgoldhua.cn' + res.image0[i].img;
    }
    let {imgs} = this.data
    //前后端沟通更好的话 实际上结构更简单
    for(let i=0;i<imgs.length;i++){
      console.log(res[`image${i+1}`])
      for(let j=0;j<res[`image${i+1}`].length||0;j++)
        imgs[i].imgArr.push(res[`image${i+1}`][j].img)
    }
    console.log(imgs)
    this.setData({
      imgs,
      imgarray: temp0,
      shop_name: res.data[0].shop_name,
      shop_addr: res.data[0].shop_addr,
      shop_tel: res.data[0].shop_tel,
      shop_time: res.data[0].shop_time
    })
  },
  previewImg:function(e){
    var index = e.currentTarget.dataset.index;
    var imgArr = this.data.imgarray;
    wx.previewImage({
      current: imgArr[index],     //当前图片地址
      urls: imgArr,               //所有要预览的图片的地址集合 数组形式
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  //修改输入框 
  modalinput: function(e){
    this.setData({
      hiddenmodalput: !this.data.hiddenmodalput,
      changeid: e.currentTarget.id
    })
    let temp = this.data.changeid;
    this.setData({
      temp: this.data[temp]
    })
  },
  //输入框取消
  cancel: function(){
    this.setData({
      hiddenmodalput: true
    });
  },
  //输入框确认
  confirm: async function(e){
    this.setData({
      hiddenmodalput:true,
    })
    let cont = this.data.changeid;
    console.log(cont,this.data[cont]);
    const res = await request({
      url: '/shoppage/change',
      data: {
        open_id: wx.getStorageSync('openid'),
        field: this.data.changeid,
        content: this.data[cont]
      }
    })
    if(res){
      console.log('修改成功')
      wx.showToast({
        title: '修改成功',
      })
    }else{
      wx.showToast({
        title: '修改失败',
      })
    }
  },
  //输入框字符输入
  bindKeyInput(e) {
    let la = this.data.changeid;
    this.setData({
      [la]: e.detail.value
    })
  },
  //改变地址 不爽的是在于要同时更改两项数据
  onChangeAddress() {
    var that = this;
    wx.chooseLocation({
      success: async function (res) {
        console.log(res)
        that.setData({
          hiddenmodalput:true,
        })
        await request({
          url: '/shoppage/change',
          data: {
            open_id: wx.getStorageSync('openid'),
            field: 'shop_addr',
            content: res.address
          }
        })
        const flag = await request({
          url: '/shoppage/change',
          data: {
            open_id: wx.getStorageSync('openid'),
            field: 'shop_jwd',
            content: res.latitude + ',' + res.longitude,
          }
        })
        if(flag){
          wx.showToast({
            title: '修改成功',
          })
          that.setData({
            shop_addr:res.address,
            shop_jwd:res.latitude + ',' + res.longitude,
          })
        }
        else
          wx.showToast({
            title: '修改失败',
          })
      },
      fail: function (err) {
        console.log(err)
      }
    });
  },
  //删除图片
  handleRemoveImg(e){
    let {imgid,index,imgsrc} = e.currentTarget.dataset
    this.delshopimg(imgid,imgsrc,index)
  },
  //删除图片
  async delshopimg(imgid,imgsrc,index){
    const res = await request({
      url: '/shoppage/del',
      method:'POST',
      data:{
        zl:`${imgid+1}`,
        img:imgsrc
      }
    });
    console.log(res)
    if(res==0){
      wx.showToast({
        title: '删除成功',
      })
      let {imgs} = this.data
      imgs[imgid].imgArr.splice(index,1)
      this.setData({
        imgs
      })
    }else{
      wx.showToast({
        title: '删除失败',
      })
    }
  },
  //点击加号选择图片
  handleChooseImg(e) {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (result) => {     
        const tempFilePaths = result.tempFilePaths
        let that = this
        let {imgid} = e.currentTarget.dataset
        //console.log(tempFilePaths[0])
        wx.uploadFile({
          url: 'https://fourgoldhua.cn/shoppage/upload', 
          filePath: tempFilePaths[0],
          name: 'file',
          header: {
            'accept': 'application/json',
            'token':`${wx.getStorageSync('openid')}`,
            'id':`${imgid+1}`
          },
          formData: {
            'user': 'test'
          },
          success (res){
            console.log(res.data)
            if(res.statusCode==200){
              wx.showToast({
                title: '上传成功',
              })
              let {imgs} = that.data
              imgs[imgid].imgArr.push(res.data)
              that.setData({
                imgs
              })
            }
          }
        })
      },
      fail: (res) => {},
      complete: (res) => {},
    })
  },
})
